﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace SHKF.B2C.MeiTuanPeiSong.Network
{
    public class SignHelper
    {
        public static string generateSign(Dictionary<string, string> parameters, string secret)
        {
            String encodeString = getEncodeString(parameters, secret);
            String sign = generateSign(encodeString);
            return sign;
        }

        private static string getEncodeString(Dictionary<string, string> parameters, string secret)
        {
            var sortedParams = from objDic in parameters
                           orderby objDic.Key
                           ascending
                           select objDic;

            StringBuilder strB = new StringBuilder(secret);

            // 排除sign和空值参数
            foreach (KeyValuePair<string, string> keyValue in sortedParams)
            {
                string key = keyValue.Key;
                if (key == "sign")
                {
                    continue;
                }

                if (keyValue.Value != null)
                {
                    strB.Append(key).Append(keyValue.Value);
                }
            }

            return strB.ToString();
        }

        private static string generateSign(String content)
        {
            return SHA1Util.Sha1(content).ToLower();
        }
    }
}
